package com.eternal.base.data.ble;

import com.eternal.framework.utils.KLog;

import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;

public class SingleMessage implements Message, SingleOnSubscribe<byte[]> {
    private SingleEmitter<byte[]> emitter;
    private Single<byte[]> single;
    private byte[] packet;

    SingleMessage(byte[] packet) {
        this.single = Single.create(this);
        this.packet = packet;
    }

    @Override
    public void onNext(byte[] data) {
        if (!isDisposed()) {
            emitter.onSuccess(data);
        }
    }

    @Override
    public void onErr(Throwable throwable) {
        if (!isDisposed()) {
            emitter.onError(throwable);
        }
    }

    @Override
    public boolean isDisposed() {
        return emitter == null || emitter.isDisposed();
    }

    @Override
    public byte[] getPacket() {
        return packet;
    }

    @Override
    public Single<byte[]> getSingle() {
        return single;
    }

    @Override
    public void subscribe(SingleEmitter<byte[]> emitter) throws Exception {
        this.emitter = emitter;
    }
}
